using MediatR;
using S.O.Api.Read.Application.Command.Medical;
using S.O.Domain.Medical;
using S.O.ErrorCode;
using S.O.Interstructrue.Base;

namespace S.O.Api.Read.Application.Handler.Medical
{
    /// <summary>
    /// 获取科室列表处理器
    /// 用于挂号时的科室选择
    /// </summary>
    public class GetDepartmentListHandler : IRequestHandler<GetDepartmentListCommand, APIResult<List<DepartmentDto>>>
    {
        /// <summary>
        /// 科室仓储
        /// </summary>
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;

        /// <summary>
        /// 构造函数，通过依赖注入初始化所需服务
        /// </summary>
        /// <param name="departmentRepository">科室仓储</param>
        public GetDepartmentListHandler(IBaseRepository<DepartmentModel> departmentRepository)
        {
            _departmentRepository = departmentRepository;
        }

        /// <summary>
        /// 处理获取科室列表命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>科室列表</returns>
        public async Task<APIResult<List<DepartmentDto>>> Handle(GetDepartmentListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 构建查询条件
                var query = _departmentRepository.GetALL();
                
                // 如果只返回启用的科室
                if (request.OnlyEnabled)
                {
                    query = query.Where(d => d.IsEnable);
                }
                
                // 按排序号排序
                query = query.OrderBy(d => d.SortOrder).ThenBy(d => d.DepartmentName);
                
                // 执行查询
                var departments = query.ToList();
                
                // 转换为DTO
                var dtoList = departments.Select(d => new DepartmentDto
                {
                    Id = d.Id,
                    DepartmentCode = d.DepartmentCode,
                    DepartmentName = d.DepartmentName,
                    Description = d.Description,
                    Location = d.Location,
                    RegistrationFee = d.RegistrationFee,
                    Director = d.Director
                }).ToList();
                
                return new APIResult<List<DepartmentDto>> { Code = APIEnums.Success, Data = dtoList, Msg = "获取科室列表成功" };
            }
            catch (Exception ex)
            {
                return new APIResult<List<DepartmentDto>> { Code = APIEnums.Error, Msg = $"获取科室列表失败：{ex.Message}" };
            }
        }
    }
}